<template>
	<view class="page-container">
		<u-navbar bgColor="#FFFFFF" :placeholder="true">
			<view slot="left" class="navbar-left">
				<view class="back-button" @click="navigateBack">
					<u-icon color="#333333" name="arrow-left" size="20"></u-icon>
					<view class="navbar-title">添加合同信息</view>
				</view>
			</view>
		</u-navbar>
		<view class="form-container">
			<view class="form-group">
				<view class="form-label">公司名称 <text class="required">*</text></view>
				<view class="form-control">
					<input type="text" v-model="formData.companyName" placeholder="请输入公司名称" class="input-field">
				</view>
			</view>
			<view class="form-group">
				<view class="form-label">合同编号 <text class="required">*</text></view>
				<view class="form-control">
					<input type="text" v-model="formData.contractNo" placeholder="请输入合同编号" class="input-field">
				</view>
			</view>
			<view class="form-group">
				<view class="form-label">申报类型 <text class="required">*</text></view>
				<view class="form-control">
					<view class="picker-trigger" @click="showDeclarePicker = true">
						<text>{{ formData.declareType || '请选择申报类型' }}</text>
						<u-icon name="arrow-down" color="#999999" size="16" class="picker-icon"></u-icon>
					</view>
					<u-picker :show="showDeclarePicker" :columns="declareTypeColumns" keyName="label"
						@confirm="handleDeclareConfirm" @cancel="showDeclarePicker = false"
						class="custom-u-picker"></u-picker>
				</view>
			</view>
			<view class="form-group">
				<view class="form-label">授权代理人 <text class="required">*</text></view>
				<view class="form-control">
					<input type="text" v-model="formData.agent" placeholder="请输入授权代理人姓名" class="input-field">
				</view>
			</view>
			<view class="form-group">
				<view class="form-label">开始日期</view>
				<view class="form-control">
					<view class="date-picker-trigger" @click="showStartDatePicker = true">
						<text>{{ formatDateText(formData.startDate) || '请选择开始日期' }}</text>
						<u-icon name="arrow-down" color="#999999" size="16" class="picker-icon"></u-icon>
					</view>
					<u-datetime-picker :show="showStartDatePicker" v-model="formData.startDate" mode="date"
						format="YYYY-MM-DD" @confirm="handleStartDateConfirm" @cancel="showStartDatePicker = false"
						class="custom-u-datetime-picker"></u-datetime-picker>
				</view>
			</view>
			<view class="form-group">
				<view class="form-label">结束日期</view>
				<view class="form-control">
					<view class="date-picker-trigger" @click="showEndDatePicker = true">
						<text>{{ formatDateText(formData.endDate) || '请选择结束日期' }}</text>
						<u-icon name="arrow-down" color="#999999" size="16" class="picker-icon"></u-icon>
					</view>
					<u-datetime-picker :show="showEndDatePicker" v-model="formData.endDate" mode="date"
						format="YYYY-MM-DD" :start-date="formData.startDate || defaultStartDate"
						@confirm="handleEndDateConfirm" @cancel="showEndDatePicker = false"
						class="custom-u-datetime-picker"></u-datetime-picker>
				</view>
			</view>
			<view class="form-group">
				<view class="form-label">合同附件 <text class="required">*</text></view>
				<view class="form-control">
					<view class="upload-container">
						<view class="upload-btn" @click="handleUpload" v-if="!formData.contractFileUrl">
							<u-icon name="plus-circle" color="#999999" size="36"></u-icon>
							<text class="upload-text">点击上传附件</text>
							<text class="upload-desc">支持PDF、Word、图片等格式，大小不超过10MB</text>
						</view>
						<view class="upload-preview" v-if="formData.contractFileUrl">
							<!-- 已替换为支持的图标名称 -->
							<u-icon :name="getFileIcon()" color="#4285F4" size="24"></u-icon>
							<text class="file-name">{{ fileName }}</text>
							<view class="upload-actions">
								<view class="action-btn" @click="handlePreviewFile">
									<u-icon name="eye" color="#666666" size="18"></u-icon>
								</view>
								<view class="action-btn" @click="handleRemoveFile">
									<u-icon name="trash" color="#FF0000" size="18"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="form-group">
				<view class="form-label">备注</view>
				<view class="form-control">
					<textarea v-model="formData.remark" placeholder="请输入备注信息" class="textarea-field"></textarea>
				</view>
			</view>
		</view>
		<u-toast ref="progressToast" :duration="0" type="loading"></u-toast>
		<u-loading-page v-if="loading" :loading-text="loadingText"></u-loading-page>
		<view class="bottom-action-bar">
			<view class="cancel-btn" @click="handleCancel">
				<text>取消</text>
			</view>
			<view class="save-btn" @click="handleSave">
				<text>保存</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				formData: {
					companyId: uni.getStorageSync('companyInfo').id || '',
					companyName: '',
					contractNo: '',
					declareType: '',
					agent: '',
					startDate: '',
					endDate: '',
					contractFileUrl: '',
					remark: '',
					signStatus: 0
				},
				declareTypeColumns: [
					[{
							label: '零申报',
							value: '零申报'
						},
						{
							label: '增值税申报',
							value: '增值税申报'
						},
						{
							label: '企业所得税申报',
							value: '企业所得税申报'
						},
						{
							label: '个人所得税申报',
							value: '个人所得税申报'
						},
						{
							label: '其他税种申报',
							value: '其他税种申报'
						}
					]
				],
				showDeclarePicker: false,
				defaultStartDate: '',
				fileName: '',
				filePath: '',
				loading: false,
				loadingText: '处理中...',
				showStartDatePicker: false,
				showEndDatePicker: false,
				http: uni.$u.http,
				companyInfo: uni.getStorageSync('companyInfo'),
				token: uni.getStorageSync('token'),
				isWechatMini: false,
				isH5: false,
				supportFileTypes: [
					'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx',
					'jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp',
					'txt', 'zip', 'rar'
				]
			};
		},
		async onLoad() {
			await this.judgeEnvironment();
			this.initFormData();
			this.checkToken();
			const currentDate = this.formatDate(new Date());
			this.formData.startDate = currentDate;
			this.formData.endDate = currentDate;
			this.defaultStartDate = currentDate;
		},
		methods: {
			async judgeEnvironment() {
				return new Promise((resolve) => {
					uni.getSystemInfo({
						success: (systemInfo) => {
							console.log('环境判断成功:', systemInfo);
							this.isWechatMini = systemInfo.uniPlatform === 'mp-weixin' ||
								systemInfo.platform === 'devtools';
							this.isH5 = !this.isWechatMini;
							console.log(`当前环境：${this.isWechatMini ? '微信小程序（含开发者工具）' : 'H5'}`);
							resolve();
						},
						fail: (err) => {
							console.error('环境判断失败:', err);
							this.isWechatMini = false;
							this.isH5 = true;
							resolve();
						}
					});
				});
			},
			initFormData() {
				const today = new Date();
				const year = today.getFullYear();
				const month = String(today.getMonth() + 1).padStart(2, '0');
				const day = String(today.getDate()).padStart(2, '0');
				const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
				this.formData.contractNo = `HT${year}${month}${day}${random}`;
				if (this.companyInfo && this.companyInfo.name) {
					this.formData.companyName = this.companyInfo.name;
				}
			},
			checkToken() {
				if (!this.token) {
					uni.$u.toast('未获取到登录状态，请重新登录');
					setTimeout(() => uni.navigateTo({
						url: '/pages/login/login'
					}), 1500);
				}
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			formatDateText(value) {
				if (!value) return '';
				if (typeof value !== 'string' && typeof value !== 'number' && !(value instanceof Date)) {
					console.warn('无效的日期值:', value);
					return '';
				}
				const date = new Date(value);
				if (isNaN(date.getTime())) {
					console.warn('无法转换为有效日期:', value);
					return '';
				}
				return this.formatDate(date);
			},
			navigateBack() {
				uni.navigateBack();
			},
			handleCancel() {
				uni.showModal({
					title: '取消确认',
					content: '确定要取消添加合同吗？已填写的信息将不会保存。',
					confirmText: '确定',
					cancelText: '取消',
					success: (res) => res.confirm && this.navigateBack()
				});
			},
			handleDeclareConfirm(e) {
				this.formData.declareType = e.value[0].value;
				this.showDeclarePicker = false;
			},
			handleStartDateConfirm(val) {
				const realVal = typeof val === 'object' && val.value !== undefined ? val.value : val;
				const formattedDate = this.formatDateText(realVal);
				this.formData.startDate = formattedDate || this.formatDate(new Date());
				this.showStartDatePicker = false;
				if (this.formData.endDate && new Date(this.formData.endDate) < new Date(formattedDate)) {
					this.formData.endDate = formattedDate;
					uni.$u.toast('结束日期已同步为开始日期（不可早于开始日期）');
				}
				this.defaultStartDate = formattedDate;
			},
			handleEndDateConfirm(val) {
				const realVal = typeof val === 'object' && val.value !== undefined ? val.value : val;
				const formattedDate = this.formatDateText(realVal);
				this.formData.endDate = formattedDate || this.formatDate(new Date());
				this.showEndDatePicker = false;
			},
			handleUpload() {
				if (!this.token) {
					uni.$u.toast('登录状态失效，请重新登录');
					return;
				}
				uni.showActionSheet({
					itemList: ['拍照', '从手机选择文件'],
					itemColor: '#333333',
					success: (res) => {
						switch (res.tapIndex) {
							case 0:
								this.takePhoto();
								break;
							case 1:
								this.chooseFile();
								break;
						}
					},
					fail: (err) => {
						console.error('选择操作失败:', err);
						uni.$u.toast('操作取消');
					}
				});
			},
			takePhoto() {
				uni.chooseImage({
					count: 1,
					sourceType: ['camera', 'album'],
					sizeType: ['original', 'compressed'],
					success: (res) => {
						console.log('拍照/选图成功:', res);
						const tempFilePath = res.tempFilePaths[0];
						const tempFile = res.tempFiles[0];
						const fileExt = tempFilePath.split('.').pop()?.toLowerCase() || 'jpg';
						this.fileName = `IMG_${new Date().getTime()}.${fileExt}`;
						this.filePath = tempFilePath;
						if (!this.checkFileSize(tempFile.size)) return;
						if (!this.checkFileFormat(fileExt)) {
							uni.$u.toast('不支持的图片格式');
							return;
						}
						this.uploadFile(tempFilePath, tempFile);
					},
					fail: (err) => {
						console.error('拍照/选图失败:', err);
						if (!err.errMsg.includes('cancel')) uni.$u.toast('拍照/选图失败，请重试');
					}
				});
			},
			chooseFile() {
				uni.chooseMessageFile({
					count: 1,
					type: 'file',
					success: (res) => {
						console.log('选择文件成功:', res);
						const tempFile = res.tempFiles[0];
						const tempFilePath = tempFile.path;
						this.fileName = tempFile.name || `FILE_${new Date().getTime()}.bin`;
						this.filePath = tempFilePath;
						if (!this.checkFileSize(tempFile.size)) return;
						const fileExt = this.fileName.split('.').pop()?.toLowerCase() || '';
						if (!this.checkFileFormat(fileExt)) {
							uni.$u.toast(`不支持的文件格式（.${fileExt}），支持${this.supportFileTypes.join('、.')}等格式`);
							return;
						}
						this.uploadFile(tempFilePath, tempFile);
					},
					fail: (err) => {
						console.error('选择文件失败:', err);
						if (!err.errMsg.includes('cancel')) uni.$u.toast('选择文件失败，请重试');
					}
				});
			},
			checkFileSize(size) {
				const maxSize = 10 * 1024 * 1024;
				if (size > maxSize) {
					uni.$u.toast(`文件过大（${(size/1024/1024).toFixed(2)}MB），请选择10MB以内的文件`);
					return false;
				}
				return true;
			},
			checkFileFormat(ext) {
				return this.supportFileTypes.includes(ext.toLowerCase());
			},
			// 核心修改：所有图标名称替换为支持的有效值
			getFileIcon() {
				if (!this.fileName) return 'file-text'; // 默认用文档图标（支持列表中无file，用file-text替代）
				const ext = this.fileName.split('.').pop()?.toLowerCase() || '';
				switch (ext) {
					case 'pdf':
					case 'doc':
					case 'docx':
					case 'xls':
					case 'xlsx':
					case 'ppt':
					case 'pptx':
					case 'txt':
						return 'file-text'; // 文档类统一用文件文本图标
					case 'jpg':
					case 'jpeg':
					case 'png':
					case 'gif':
					case 'bmp':
					case 'webp':
						return 'photo'; // 图片类用照片图标
					case 'zip':
					case 'rar':
						return 'attach'; // 压缩包用附件图标
					default:
						return 'file-text'; // 其他文件默认用文档图标
				}
			},
			uploadFile(tempFilePath, tempFile) {
				const uploadUrl = uni.$u.http.config.baseURL + 'oss/upload';
				console.log('上传地址:', uploadUrl);
				if (!this.http || !this.http.upload) {
					console.error('uView http.upload不存在');
					uni.$u.toast('上传工具初始化失败');
					return;
				}
				try {
					this.http.upload(uploadUrl, {
						filePath: tempFilePath,
						name: 'file',
						formData: {
							companyId: this.formData.companyId,
							fileName: this.fileName,
							fileSize: tempFile.size,
							fileType: tempFile.type || this.fileName.split('.').pop()?.toLowerCase() || 'file'
						},
						header: {
							'SA-TOKEN-USER': this.token,
							'Content-Type': 'multipart/form-data'
						},
						getTask: (requestTask) => {
							requestTask.onProgressUpdate((res) => {
								console.log('上传进度:', res.progress + '%');
								this.$refs.progressToast.show({
									title: res.progress < 100 ? `上传中：${res.progress}%` :
										'保存中...',
									type: 'loading'
								});
							});
						}
					}).then((res) => {
						console.log('上传接口返回:', res);
						this.$refs.progressToast.hide();
						if (res.code === 200) {
							this.formData.contractFileUrl = res.data;
							uni.$u.toast('文件上传成功');
						} else {
							uni.$u.toast(`上传失败：${res.msg || '接口返回异常'}`);
						}
					}).catch((err) => {
						console.error('上传异常:', err);
						this.$refs.progressToast.hide();
						uni.$u.toast(`上传异常：${err.message || '网络错误'}`);
					});
				} catch (err) {
					console.error('上传方法执行异常:', err);
					this.$refs.progressToast.hide();
					uni.$u.toast('上传失败，请重试');
				}
			},
			handlePreviewFile() {
				if (!this.formData.contractFileUrl) {
					uni.$u.toast('文件不存在');
					return;
				}
				this.loading = true;
				const ext = this.fileName.split('.').pop()?.toLowerCase() || '';
				const isImage = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'].includes(ext);
				const isDoc = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'].includes(ext);
				uni.downloadFile({
					url: this.formData.contractFileUrl,
					header: {
						'SA-TOKEN-USER': this.token
					},
					success: (downloadRes) => {
						this.loading = false;
						if (downloadRes.statusCode === 200) {
							const tempFilePath = downloadRes.tempFilePath;
							if (isImage) {
								uni.previewImage({
									urls: [tempFilePath],
									current: tempFilePath,
									success: () => console.log('图片预览成功'),
									fail: (err) => {
										console.error('图片预览失败:', err);
										uni.$u.toast('预览失败，请重试');
									}
								});
							} else if (isDoc) {
								uni.openDocument({
									filePath: tempFilePath,
									showMenu: true,
									success: () => console.log('文档预览成功'),
									fail: (err) => {
										console.error('文档预览失败:', err);
										uni.$u.toast('预览失败，请安装对应的文档查看器');
									}
								});
							} else {
								uni.showActionSheet({
									itemList: ['下载文件'],
									success: () => {
										uni.saveFile({
											tempFilePath: tempFilePath,
											success: (saveRes) => uni.$u.toast(
												`文件已保存至：${saveRes.savedFilePath}`),
											fail: (err) => {
												console.error('文件保存失败:', err);
												uni.$u.toast('文件下载失败，请重试');
											}
										});
									}
								});
							}
						} else {
							uni.$u.toast(`文件加载失败（${downloadRes.statusCode}）`);
						}
					},
					fail: (err) => {
						this.loading = false;
						console.error('下载文件失败:', err);
						uni.$u.toast('预览异常，请重试');
					}
				});
			},
			handleRemoveFile() {
				this.formData.contractFileUrl = '';
				this.fileName = '';
				this.filePath = '';
				uni.$u.toast('文件已删除');
			},
			validateForm() {
				if (!this.token) {
					uni.$u.toast('未获取到登录状态');
					return false;
				}
				if (!this.formData.companyId) {
					uni.$u.toast('未获取到公司信息');
					return false;
				}
				if (!this.formData.companyName.trim()) {
					uni.$u.toast('请输入公司名称');
					return false;
				}
				if (!this.formData.contractNo.trim()) {
					uni.$u.toast('请输入合同编号');
					return false;
				}
				if (!this.formData.declareType) {
					uni.$u.toast('请选择申报类型');
					return false;
				}
				if (!this.formData.agent.trim()) {
					uni.$u.toast('请输入授权代理人');
					return false;
				}
				if (!this.formData.contractFileUrl) {
					uni.$u.toast('请上传合同附件');
					return false;
				}
				return true;
			},
			async handleSave() {
				if (!this.validateForm()) return;
				this.loading = true;
				try {
					const res = await this.http.post('/VipVipcontract', {
						companyId: this.formData.companyId,
						companyName: this.formData.companyName,
						contractNo: this.formData.contractNo,
						declareType: this.formData.declareType,
						agent: this.formData.agent,
						startDate: this.formData.startDate || null,
						endDate: this.formData.endDate || null,
						contractFileUrl: this.formData.contractFileUrl,
						remark: this.formData.remark || '',
						signStatus: 0
					}, {
						headers: {
							'SA-TOKEN-USER': this.token
						}
					});
					if (res.code === 200) {
						uni.$u.toast('保存成功');
						setTimeout(() => {
							uni.navigateBack({
								success: () => {
									const prevPage = getCurrentPages()[getCurrentPages().length -
										2];
									prevPage && prevPage.getContractList && prevPage
										.getContractList();
								}
							});
						}, 1000);
					} else {
						uni.$u.toast(res.msg || '保存失败');
					}
				} catch (err) {
					console.error('保存异常:', err);
					uni.$u.toast('网络错误，请重试');
				} finally {
					this.loading = false;
				}
			}
		}
	};
</script>

<style scoped>
	.page-container {
		min-height: 100vh;
		background-color: #F5F7FA;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
		padding: 0 10px;
		box-sizing: border-box;
	}

	.navbar-left {
		display: flex;
		align-items: center;
	}

	.back-button {
		display: flex;
		align-items: center;
	}

	.navbar-title {
		font-size: 18px;
		font-weight: 600;
		color: #4285F4;
		margin-left: 8px;
	}

	.form-container {
		padding: 16px 0;
		max-width: 100%;
		box-sizing: border-box;
	}

	.form-group {
		margin-bottom: 20px;
		width: 100%;
		box-sizing: border-box;
	}

	.form-label {
		font-size: 14px;
		color: #333;
		margin-bottom: 8px;
		display: block;
	}

	.required {
		color: #FF0000;
	}

	.form-control {
		width: 100%;
		box-sizing: border-box;
	}

	.input-field {
		width: 100%;
		height: 44px;
		border: 1px solid #EEE;
		border-radius: 6px;
		padding: 0 12px;
		font-size: 14px;
		background-color: #FFF;
		box-sizing: border-box;
	}

	.picker-trigger,
	.date-picker-trigger {
		width: 100%;
		height: 44px;
		border: 1px solid #EEE;
		border-radius: 6px;
		padding: 0 12px;
		font-size: 14px;
		background-color: #FFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		box-sizing: border-box;
	}

	.picker-icon {
		margin-left: 8px;
	}

	.textarea-field {
		width: 100%;
		min-height: 100px;
		border: 1px solid #EEE;
		border-radius: 6px;
		padding: 12px;
		font-size: 14px;
		background-color: #FFF;
		resize: none;
		box-sizing: border-box;
	}

	.upload-container {
		width: 100%;
		box-sizing: border-box;
	}

	.upload-btn {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		height: 120px;
		border: 1px dashed #DDD;
		border-radius: 6px;
		background-color: #F9F9F9;
		box-sizing: border-box;
	}

	.upload-text {
		font-size: 14px;
		color: #666;
		margin-top: 8px;
	}

	.upload-desc {
		font-size: 12px;
		color: #999;
		margin-top: 4px;
		text-align: center;
		width: 90%;
	}

	.upload-preview {
		display: flex;
		align-items: center;
		height: 60px;
		border: 1px solid #EEE;
		border-radius: 6px;
		padding: 0 12px;
		background-color: #FFF;
		box-sizing: border-box;
	}

	.file-name {
		flex: 1;
		font-size: 14px;
		color: #333;
		margin-left: 12px;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}

	.upload-actions {
		display: flex;
	}

	.action-btn {
		width: 36px;
		height: 36px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.bottom-action-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 56px;
		background-color: #FFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 16px;
		box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
		z-index: 99;
		box-sizing: border-box;
	}

	.cancel-btn {
		width: 46%;
		height: 40px;
		background-color: #F5F7FA;
		color: #333;
		border-radius: 6px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		box-sizing: border-box;
	}

	.save-btn {
		width: 46%;
		height: 40px;
		background-color: #4285F4;
		color: #FFF;
		border-radius: 6px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 16px;
		box-sizing: border-box;
	}

	::v-deep .custom-u-picker {
		z-index: 1000 !important;
		width: 100% !important;
	}

	::v-deep .custom-u-datetime-picker {
		z-index: 1000 !important;
		width: 100% !important;
	}
</style>